Vue で radio グループをいい感じに実装
code:vue
<script setup lang="ts">
import { ref } from "vue";
import Radio from "./Radio.vue"
const selected = ref<typeof optionsnumber>("fuga"); </script>
<template>
<div>
<Radio
:options
name="hogefugapiyo"
v-model="selected"
/>
{{ selected }}
</div>
</template>
ってやると、親側で options と selected のことについて知らないといけない
そこで
code:vue
<script lang="ts">
import { ref } from "vue";
export function useRadio<
const U extends readonly (string | number | boolean)[]
(options: U, initial?: Unumber) { return {
options,
selected: ref<Unumber>(initial ?? options0), };
}
</script>
<script setup lang="ts" generic="T extends string | number | boolean">
const model = defineModel<T>({ required: true });
const props = defineProps<{
options: readonly T[];
name: string;
legend?: string;
}>();
</script>
<template>
<fieldset>
<legend v-if="props.legend">{{ props.legend }}</legend>
<template
v-for="option in props.options"
:key="option.toString()"
<input
type="radio"
:id="${name}-${option.toString()}"
:name="props.name"
:value="option"
v-model="model"
/>
<label
:for="${name}-${option.toString()}"
{{ option }}
</label>
</template>
</fieldset>
</template>